<?php

namespace app\common\controller;

use app\common\library\Auth;
use app\common\library\token\TokenExpirationException;
use ba\Exception;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\facade\Event;
use think\Model;
use Throwable;

class Frontend extends Api
{
    /**
     * 无需登录的方法
     * 访问本控制器的此方法，无需会员登录
     * @var array
     */
    protected array $noNeedLogin = [];

    /**
     * 无需鉴权的方法
     * @var array
     */
    protected array $noNeedPermission = [];

    protected Model $model;
    /**
     * 权限类实例
     * @var Auth
     */
    protected Auth $auth;

    private static string $platform;

    private const  PLATFORM_AUTH_CONFIG = [
        'client' => [
            'auth' => \app\client\library\Auth::class,
            'token_name' => ['ba', 'client', 'token'],
        ],
        'organization' => [
            'auth' => \app\organization\library\Auth::class,
            'token_name' => ['ba', 'organization', 'token'],
        ],
        'teacher' => [
            'auth' => \app\teacher\library\Auth::class,
            'token_name' => ['ba', 'teacher', 'token'],
        ],
        'common' => [
            'auth' => \app\comapi\library\Auth::class,
            'token_name' => ['ba', 'common', 'token'],
        ],
    ];


    /**
     * 初始化
     * @throws Throwable
     * @throws HttpResponseException
     */
    public function initialize(): void
    {
        parent::initialize();

        $needLogin = !action_in_arr($this->noNeedLogin);

        try {
            self::$platform = $this->request->header('platform', 'common');
            $auth = self::getPlatformAuth();

            // 初始化会员鉴权实例
            $this->auth = $auth['auth']::instance();
            $token = get_auth_token($auth['token_name']);
            if ($token) {
                $res = $this->auth->init($token);
                if (!$res) {
                    throw new ValidateException($this->auth->getError());
                }
            }
        } catch (TokenExpirationException) {
            if ($needLogin) {
                $this->fail(__('Token expiration'), null, $this->auth::PERMISSION_RESPONSE_CODE, self::SILENT);
            }
        } catch (ValidateException $e) {
            if ($needLogin) {
                $this->fail($e->getMessage(), null, 409, self::SILENT);
            }
        } catch (Exception $e) {
            $this->fail($e->getMessage(), null, 409, self::SILENT);
        }


        if ($needLogin) {
            if (!$this->auth->isLogin()) {
                $this->fail(__('Please login first'), null, $this->auth::LOGIN_RESPONSE_CODE, self::SILENT);
            }
            // if (!action_in_arr($this->noNeedPermission)) {
            //     $routePath = ($this->app->request->controllerPath ?? '') . '/' . $this->request->action(true);
            //     if (!$this->auth->check($routePath)) {
            //         $this->fail(__('You have no permission'), null, $this->auth::LOGIN_RESPONSE_CODE);
            //     }
            // }
        }

        // 会员验权和登录标签位
        Event::trigger('frontendInit', $this->auth);
    }

    /**
     * @throws Exception
     */
    public static function getPlatformAuth($platform = ''): array
    {
        $platform = $platform ?: self::$platform;
        if (!$platform) {
            throw new Exception('请选择平台');
        }
        if (!array_key_exists($platform, self::PLATFORM_AUTH_CONFIG)) {
            throw new Exception('平台不存在');
        }

        return self::PLATFORM_AUTH_CONFIG[$platform];
    }
}